package com.pikaqiu.blog.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author 吕梁山
 * @date 2019-01-12
 */
public class DateUtil {

    public static SimpleDateFormat simpleDateFormat_yMdHms = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static SimpleDateFormat simpleDateFormat_yMd = new SimpleDateFormat("yyyy-M-d");
    public static SimpleDateFormat simpleDateFormat_Md = new SimpleDateFormat("M-d");

    /**
     * 获取一个时间距当前时间有多久
     */
    public static String getDateBeforeNow(Date date) {

        long second = 1000;
        long minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
        long hour = minute * 60;
        long day = hour * 24;

        long time = date.getTime();
        Calendar now = Calendar.getInstance();
        int now_year =  now.get(Calendar.YEAR);
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int comment_year = instance.get(Calendar.YEAR);
        long time1 = now.getTime().getTime();
        long diffValue = time1 - time;

        long secondC = diffValue / second;
        long minC = diffValue / minute;  //计算时间差的分，时，天，周，月
        long hourC = diffValue / hour;
        long dayC = diffValue / day;


        if(dayC > 7){
            if(now_year == comment_year){
                return simpleDateFormat_Md.format(date);
            } else {
                return simpleDateFormat_yMd.format(date);
            }
        } else if(dayC > 0) {
            return dayC + "天前";
        } else if (hourC > 0){
            return hourC + "小时前";
        } else if (minC > 0){
            return minC + "分钟前";
        } else if (secondC >= 0){
            return secondC + "秒钟前";
        } else {
            return simpleDateFormat_yMd.format(date);
        }
    }
}
